package com.wontube.core.pub.servlet.handlers;

import java.sql.SQLException;

import org.apache.ibatis.session.SqlSession;

import com.wontube.client.modle.vo.ClientSession;
import com.wontube.core.dao.DatasourceContext;
import com.wontube.core.dao.SqlSessionManager;
import com.wontube.core.pub.IUserInfo;
import com.wontube.core.pub.ServerContext;

/**
 * @author yuechao
 * 
 *         请求处理的基类，用于需要数据库操作的情况
 * 
 */
public abstract class DynamicDbHandler extends AbstractHander {
	/**
	 * 取得数据源 SqlMap 配置
	 * 
	 * 一个请求开始时直到请求结束，返回的是同一个实例
	 * 
	 * 不同的请求返回不同的实例
	 * 
	 */
	@Override
	public final SqlSession getSqlSession(boolean autoCommit) throws SQLException {
		SqlSession session = DatasourceContext.getSqlSession();

		if (session != null) {
			return session;
		}

		ServerContext context = super.getContext();
		ClientSession clientSession = context.getSession();
		if (clientSession == null) {
			return null;
		}

		IUserInfo user = (IUserInfo)clientSession.getProperty("user");
		String datasourceId = user.getDatasourceId();
		if (datasourceId == null) {
			return null;
		}
		
		return SqlSessionManager.manager.get(datasourceId, autoCommit);
	}

	/**
	 * 取得Mapper代理, 注意，此方法只能在请求期间才可以使用
	 * 
	 * @return
	 */
	protected <T> T getMapper(Class<T> type) {
		SqlSession session = DatasourceContext.getSqlSession();
		return session.getMapper(type);
	}
}
